package com.project.demo.controller;

import com.project.demo.entity.UserParticipation;
import com.project.demo.service.UserParticipationService;
import com.project.demo.service.UserParticipationAttendeeService;
import com.project.demo.service.PaymentService;
import com.project.demo.controller.base.BaseController;
import com.project.demo.constant.FindConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


/**
 * 用户参会：(UserParticipation)表控制层
 *
 */
@Slf4j
@RestController
@RequestMapping("/user_participation")
public class UserParticipationController extends BaseController<UserParticipation, UserParticipationService> {

    /**
     * 支付服务
     */
    @Autowired
    private PaymentService paymentService;

    /**
     * 参会人信息服务
     */
    @Autowired
    private UserParticipationAttendeeService attendeeService;

    /**
     * 会议信息服务（用于JOIN查询）
     */
    @Autowired
    private com.project.demo.service.MeetingInformationService meetingInformationService;

    /**
     * 用户参会对象
     */
    @Autowired
    public UserParticipationController(UserParticipationService service) {
        setService(service);
    }


    @PostMapping("/add")
    @Transactional
    public Map<String, Object> add(HttpServletRequest request) throws IOException {
        Map<String,Object> paramMap = service.readBody(request.getReader());
        
        // 记录提交的数据，用于调试
        log.info("收到报名提交请求，数据：{}", paramMap);
        
        // 验证必要字段
        if (paramMap.get("participants") == null || paramMap.get("participants").toString().equals("0")) {
            log.warn("报名提交缺少 participants 字段或值为0");
            return error(400, "报名信息缺少用户ID，请先登录");
        }
        
        if (paramMap.get("meeting_information_id") == null) {
            log.warn("报名提交缺少 meeting_information_id 字段");
            return error(400, "报名信息缺少会议ID");
        }
        
        // 移除冗余字段（如果前端仍然提交了）
        paramMap.remove("meeting_number");
        paramMap.remove("conference_name");
        paramMap.remove("meeting_type");
        paramMap.remove("meeting_time");
        paramMap.remove("meeting_venue");
        paramMap.remove("user_name");
        
        // 确保必要字段有默认值
        if (paramMap.get("pay_state") == null || paramMap.get("pay_state").toString().isEmpty()) {
            paramMap.put("pay_state", "未支付");
        }
        if (paramMap.get("examine_state") == null || paramMap.get("examine_state").toString().isEmpty()) {
            paramMap.put("examine_state", "未审核");
        }
        
        // 处理 accommodation_or_not：如果是字符串，转换为整数
        if (paramMap.get("accommodation_or_not") != null) {
            Object accValue = paramMap.get("accommodation_or_not");
            if (accValue instanceof String) {
                String accStr = accValue.toString();
                if (accStr.equals("是") || accStr.equalsIgnoreCase("true") || accStr.equals("1") || accStr.equalsIgnoreCase("yes")) {
                    paramMap.put("accommodation_or_not", 1);
                } else {
                    paramMap.put("accommodation_or_not", 0);
                }
            }
        } else {
            paramMap.put("accommodation_or_not", 0);
        }
        
        // 提取参会人信息（如果有）
        Object attendeesDataObj = paramMap.remove("attendees_data");
        String attendeesDataStr = null;
        if (attendeesDataObj != null) {
            if (attendeesDataObj instanceof String) {
                attendeesDataStr = (String) attendeesDataObj;
            } else {
                attendeesDataStr = attendeesDataObj.toString();
            }
        }
        
        // 执行插入
        Integer userParticipationId = null;
        try {
            service.insert(paramMap);
            log.info("报名数据插入成功");
            
            // 查询刚插入的记录
        Map<String, String> query = new HashMap<>();
            if (paramMap.get("participants") != null) {
                query.put("participants", paramMap.get("participants").toString());
            }
            if (paramMap.get("meeting_information_id") != null) {
                query.put("meeting_information_id", paramMap.get("meeting_information_id").toString());
            }
            
        Map<String, String> config = new HashMap<>();
            config.put(FindConfig.ORDER_BY, "create_time desc");
            config.put(FindConfig.SIZE, "1");
        
        Query select = service.select(query, config);
            List resultList = select != null ? select.getResultList() : null;
        
        if (resultList != null && resultList.size() > 0) {
                Object firstResult = resultList.get(0);
                if (firstResult instanceof UserParticipation) {
                    UserParticipation up = (UserParticipation) firstResult;
                    userParticipationId = up.getUser_participation_id();
                    log.info("成功获取新插入记录的 user_participation_id: {}", userParticipationId);
                } else if (firstResult instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> upMap = (Map<String, Object>) firstResult;
                    Object idObj = upMap.get("user_participation_id");
                    if (idObj != null) {
                        userParticipationId = Integer.parseInt(idObj.toString());
                        log.info("成功获取新插入记录的 user_participation_id (Map): {}", userParticipationId);
                    }
                }
            }
            
            if (userParticipationId == null) {
                log.error("无法获取新插入记录的 user_participation_id");
                return error(500, "保存报名信息失败：无法获取报名记录ID");
            }
            
            // 处理参会人信息：迁移到新表
            if (attendeesDataStr != null && !attendeesDataStr.isEmpty()) {
                try {
                    com.alibaba.fastjson.JSONArray attendeesArray = com.alibaba.fastjson.JSON.parseArray(attendeesDataStr);
                    if (attendeesArray != null && attendeesArray.size() > 0) {
                        log.info("开始迁移参会人信息到新表，共 {} 条", attendeesArray.size());
                        for (int i = 0; i < attendeesArray.size(); i++) {
                            com.alibaba.fastjson.JSONObject attendeeObj = attendeesArray.getJSONObject(i);
                            Map<String, Object> attendeeMap = new HashMap<>();
                            attendeeMap.put("user_participation_id", userParticipationId);
                            attendeeMap.put("name", attendeeObj.getString("name"));
                            attendeeMap.put("email", attendeeObj.getString("email"));
                            attendeeMap.put("phone", attendeeObj.getString("phone"));
                            attendeeMap.put("phone_code", attendeeObj.getString("phoneCode") != null ? attendeeObj.getString("phoneCode") : "+86");
                            attendeeMap.put("affiliation", attendeeObj.getString("affiliation"));
                            attendeeMap.put("affiliation_en", attendeeObj.getString("affiliationEn"));
                            attendeeMap.put("title", attendeeObj.getString("title"));
                            attendeeMap.put("speech_title", attendeeObj.getString("speechTitle"));
                            attendeeMap.put("id_card", attendeeObj.getString("idCard"));
                            attendeeMap.put("wechat", attendeeObj.getString("wechat"));
                            attendeeMap.put("participation_type", attendeeObj.getString("participationType") != null ? attendeeObj.getString("participationType") : "onsite");
                            // 处理 accommodation
                            Object accObj = attendeeObj.get("accommodation");
                            if (accObj instanceof Boolean) {
                                attendeeMap.put("accommodation", ((Boolean) accObj) ? 1 : 0);
                            } else if (accObj instanceof String) {
                                String accStr = (String) accObj;
                                attendeeMap.put("accommodation", (accStr.equals("true") || accStr.equals("1") || accStr.equals("是")) ? 1 : 0);
                            } else {
                                attendeeMap.put("accommodation", 0);
                            }
                            
                            attendeeService.insert(attendeeMap);
                            log.info("成功插入参会人信息[{}]: {}", i, attendeeObj.getString("name"));
                        }
                        log.info("参会人信息迁移完成");
                    }
                } catch (Exception e) {
                    log.error("迁移参会人信息失败", e);
                    // 不阻止整个流程，继续执行
                }
            }
            
            log.info("报名提交成功，user_participation_id: {}", userParticipationId);
            Map<String, Object> result = new HashMap<>();
            result.put("user_participation_id", userParticipationId);
            return success(result);
            
        } catch (Exception e) {
            log.error("报名数据插入失败", e);
            return error(500, "保存报名信息失败: " + e.getMessage());
        }
    }

    /**
     * 获取报名信息（包含会议信息）- 使用JOIN查询
     * 注意：此方法等同于obj方法，保留用于兼容性
     */
    @RequestMapping("/get_with_meeting")
    public Map<String, Object> getWithMeeting(HttpServletRequest request) {
        // 调用父类方法获取基础数据，然后添加会议信息（避免递归）
        Map<String, Object> result = super.obj(request);
        
        // 添加会议信息和参会人信息
        if (result != null && result.get("result") != null) {
            Object resultObj = result.get("result");
            if (resultObj instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> resultMap = (Map<String, Object>) resultObj;
                Object obj = resultMap.get("obj");
                if (obj instanceof UserParticipation) {
                    UserParticipation up = (UserParticipation) obj;
                    enrichWithMeetingInfo(up, resultMap);
                } else if (obj instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> upMap = (Map<String, Object>) obj;
                    enrichWithMeetingInfoMap(upMap);
                }
                
                // 加载参会人信息
                Object upIdObj = resultMap.get("obj");
                Integer upId = null;
                if (upIdObj instanceof UserParticipation) {
                    upId = ((UserParticipation) upIdObj).getUser_participation_id();
                } else if (upIdObj instanceof Map) {
                    Object idObj = ((Map<?, ?>) upIdObj).get("user_participation_id");
                    if (idObj != null) {
                        upId = Integer.parseInt(idObj.toString());
                    }
                }
                
                if (upId != null) {
                    Map<String, String> attendeeQuery = new HashMap<>();
                    attendeeQuery.put("user_participation_id", upId.toString());
                    Map<String, String> attendeeConfig = new HashMap<>();
                    Query attendeeQueryResult = attendeeService.select(attendeeQuery, attendeeConfig);
                    List attendeeList = attendeeQueryResult != null ? attendeeQueryResult.getResultList() : null;
                    if (attendeeList != null) {
                        resultMap.put("attendees", attendeeList);
                    }
                }
            }
        }
        
        return result;
    }
    
    /**
     * 辅助方法：为UserParticipation对象添加会议信息
     */
    private void enrichWithMeetingInfo(UserParticipation up, Map<String, Object> resultMap) {
        if (up.getMeeting_information_id() != null) {
            try {
                Map<String, String> meetingQuery = new HashMap<>();
                meetingQuery.put("meeting_information_id", up.getMeeting_information_id().toString());
                Map<String, String> meetingConfig = new HashMap<>();
                Query meetingQueryResult = meetingInformationService.select(meetingQuery, meetingConfig);
                List meetingList = meetingQueryResult != null ? meetingQueryResult.getResultList() : null;
                if (meetingList != null && meetingList.size() > 0) {
                    Object meetingObj = meetingList.get(0);
                    if (meetingObj instanceof com.project.demo.entity.MeetingInformation) {
                        com.project.demo.entity.MeetingInformation mi = (com.project.demo.entity.MeetingInformation) meetingObj;
                        Map<String, Object> meetingInfo = new HashMap<>();
                        meetingInfo.put("meeting_number", mi.getMeeting_number());
                        meetingInfo.put("conference_name", mi.getConference_name());
                        meetingInfo.put("meeting_type", mi.getMeeting_type());
                        // 格式化会议时间为字符串
                        if (mi.getMeeting_time() != null) {
                            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            meetingInfo.put("meeting_time", sdf.format(mi.getMeeting_time()));
                        } else {
                            meetingInfo.put("meeting_time", null);
                        }
                        meetingInfo.put("meeting_venue", mi.getMeeting_venue());
                        meetingInfo.put("amount_of_participation", mi.getAmount_of_participation());
                        resultMap.put("meeting_info", meetingInfo);
                    }
                }
            } catch (Exception e) {
                log.warn("获取会议信息失败", e);
            }
        }
    }
    
    /**
     * 辅助方法：为Map对象添加会议信息
     */
    private void enrichWithMeetingInfoMap(Map<String, Object> upMap) {
        Object meetingIdObj = upMap.get("meeting_information_id");
        if (meetingIdObj != null) {
            try {
                Integer meetingId = Integer.parseInt(meetingIdObj.toString());
                Map<String, String> meetingQuery = new HashMap<>();
                meetingQuery.put("meeting_information_id", meetingId.toString());
                Map<String, String> meetingConfig = new HashMap<>();
                Query meetingQueryResult = meetingInformationService.select(meetingQuery, meetingConfig);
                List meetingList = meetingQueryResult != null ? meetingQueryResult.getResultList() : null;
                if (meetingList != null && meetingList.size() > 0) {
                    Object meetingObj = meetingList.get(0);
                    if (meetingObj instanceof com.project.demo.entity.MeetingInformation) {
                        com.project.demo.entity.MeetingInformation mi = (com.project.demo.entity.MeetingInformation) meetingObj;
                        upMap.put("meeting_number", mi.getMeeting_number());
                        upMap.put("conference_name", mi.getConference_name());
                        upMap.put("meeting_type", mi.getMeeting_type());
                        // 格式化会议时间为字符串
                        if (mi.getMeeting_time() != null) {
                            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            upMap.put("meeting_time", sdf.format(mi.getMeeting_time()));
                        } else {
                            upMap.put("meeting_time", null);
                        }
                        upMap.put("meeting_venue", mi.getMeeting_venue());
                        // 使用会议信息中的金额（如果需要）
                        if (upMap.get("amount_of_participation") == null) {
                            upMap.put("amount_of_participation", mi.getAmount_of_participation());
                        }
                    }
                }
            } catch (Exception e) {
                log.warn("获取会议信息失败", e);
            }
        }
    }
    
    /**
     * 重写get_obj方法（覆盖父类的obj方法），默认包含会议信息
     */
    @Override
    @RequestMapping("/get_obj")
    public Map<String, Object> obj(HttpServletRequest request) {
        // 调用父类方法获取基础数据，然后添加会议信息
        Map<String, Object> result = super.obj(request);
        
        // 添加会议信息和参会人信息
        if (result != null && result.get("result") != null) {
            Object resultObj = result.get("result");
            if (resultObj instanceof Map) {
                @SuppressWarnings("unchecked")
                Map<String, Object> resultMap = (Map<String, Object>) resultObj;
                Object objValue = resultMap.get("obj");
                if (objValue instanceof UserParticipation) {
                    UserParticipation up = (UserParticipation) objValue;
                    enrichWithMeetingInfo(up, resultMap);
                    
                    // 确保 meeting_information_id 在 resultMap 中
                    if (up.getMeeting_information_id() != null) {
                        resultMap.put("meeting_information_id", up.getMeeting_information_id());
                    }
                    
                    // 加载参会人信息
                    Integer upId = up.getUser_participation_id();
                    if (upId != null) {
                        Map<String, String> attendeeQuery = new HashMap<>();
                        attendeeQuery.put("user_participation_id", upId.toString());
                        Map<String, String> attendeeConfig = new HashMap<>();
                        Query attendeeQueryResult = attendeeService.select(attendeeQuery, attendeeConfig);
                        List attendeeList = attendeeQueryResult != null ? attendeeQueryResult.getResultList() : null;
                        if (attendeeList != null) {
                            resultMap.put("attendees", attendeeList);
                            
                            // 为了兼容前端，也设置 user_name（取第一个参会人姓名）
                            if (attendeeList.size() > 0) {
                                Object firstAttendee = attendeeList.get(0);
                                if (firstAttendee instanceof com.project.demo.entity.UserParticipationAttendee) {
                                    com.project.demo.entity.UserParticipationAttendee attendee = (com.project.demo.entity.UserParticipationAttendee) firstAttendee;
                                    resultMap.put("user_name", attendee.getName());
                                } else if (firstAttendee instanceof Map) {
                                    @SuppressWarnings("unchecked")
                                    Map<String, Object> attendeeMap = (Map<String, Object>) firstAttendee;
                                    resultMap.put("user_name", attendeeMap.get("name"));
                                }
                            }
                        }
                    }
                } else if (objValue instanceof Map) {
                    @SuppressWarnings("unchecked")
                    Map<String, Object> upMap = (Map<String, Object>) objValue;
                    enrichWithMeetingInfoMap(upMap);
                    
                    // 确保 meeting_information_id 存在
                    if (upMap.get("meeting_information_id") == null) {
                        Object upIdObj = upMap.get("user_participation_id");
                        if (upIdObj != null) {
                            // 如果 meeting_information_id 不存在，尝试从数据库查询
                            try {
                                Integer upId = Integer.parseInt(upIdObj.toString());
                                Map<String, String> query = new HashMap<>();
                                query.put("user_participation_id", upId.toString());
                                Map<String, String> config = new HashMap<>();
                                Query selectResult = service.select(query, config);
                                Object upObj = selectResult != null && selectResult.getResultList().size() > 0 
                                    ? selectResult.getResultList().get(0) : null;
                                if (upObj instanceof UserParticipation) {
                                    upMap.put("meeting_information_id", ((UserParticipation) upObj).getMeeting_information_id());
                                }
                            } catch (Exception e) {
                                log.warn("获取 meeting_information_id 失败", e);
                            }
                        }
                    }
                    
                    // 加载参会人信息
                    Object upIdObj = upMap.get("user_participation_id");
                    Integer upId = null;
                    if (upIdObj != null) {
                        upId = Integer.parseInt(upIdObj.toString());
                    }
                    if (upId != null) {
                        Map<String, String> attendeeQuery = new HashMap<>();
                        attendeeQuery.put("user_participation_id", upId.toString());
                        Map<String, String> attendeeConfig = new HashMap<>();
                        Query attendeeQueryResult = attendeeService.select(attendeeQuery, attendeeConfig);
                        List attendeeList = attendeeQueryResult != null ? attendeeQueryResult.getResultList() : null;
                        if (attendeeList != null) {
                            resultMap.put("attendees", attendeeList);
                            
                            // 为了兼容前端，也设置 user_name（取第一个参会人姓名）
                            if (attendeeList.size() > 0) {
                                Object firstAttendee = attendeeList.get(0);
                                if (firstAttendee instanceof com.project.demo.entity.UserParticipationAttendee) {
                                    com.project.demo.entity.UserParticipationAttendee attendee = (com.project.demo.entity.UserParticipationAttendee) firstAttendee;
                                    upMap.put("user_name", attendee.getName());
                                    resultMap.put("user_name", attendee.getName());
                                } else if (firstAttendee instanceof Map) {
                                    @SuppressWarnings("unchecked")
                                    Map<String, Object> attendeeMap = (Map<String, Object>) firstAttendee;
                                    Object nameObj = attendeeMap.get("name");
                                    if (nameObj != null) {
                                        upMap.put("user_name", nameObj.toString());
                                        resultMap.put("user_name", nameObj.toString());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        
        return result;
    }
    
    /**
     * 获取列表（包含会议信息）
     */
    @RequestMapping("/get_list")
    public Map<String, Object> getList(HttpServletRequest request) {
        // 检查是否需要包含会议信息（默认包含）
        String includeMeeting = request.getParameter("include_meeting_info");
        if (includeMeeting != null && "false".equals(includeMeeting)) {
            return super.getList(request);
        } else {
            return getListWithMeeting(request);
        }
    }
    
    /**
     * 获取列表（JOIN会议信息）
     */
    @RequestMapping("/get_list_with_meeting")
    public Map<String, Object> getListWithMeeting(HttpServletRequest request) {
        try {
            Map<String, String> query = service.readQuery(request);
            Map<String, String> config = service.readConfig(request);
            
            // 处理跨表查询：如果查询条件中包含会议相关字段，先查询会议信息
            String meetingNumber = query.remove("meeting_number");
            String conferenceName = query.remove("conference_name");
            
            // 如果查询条件中包含会议相关字段，先查询会议信息获取 meeting_information_id
            if (meetingNumber != null && !meetingNumber.isEmpty()) {
                Map<String, String> meetingQuery = new HashMap<>();
                meetingQuery.put("meeting_number", meetingNumber);
                Map<String, String> meetingConfig = new HashMap<>();
                Query meetingResult = meetingInformationService.select(meetingQuery, meetingConfig);
                List<?> meetingList = meetingResult != null ? meetingResult.getResultList() : null;
                if (meetingList != null && meetingList.size() > 0) {
                    Object meetingObj = meetingList.get(0);
                    if (meetingObj instanceof com.project.demo.entity.MeetingInformation) {
                        Integer meetingId = ((com.project.demo.entity.MeetingInformation) meetingObj).getMeeting_information_id();
                        if (meetingId != null) {
                            query.put("meeting_information_id", meetingId.toString());
                        }
                    }
                } else {
                    // 如果没有找到匹配的会议，返回空列表
                    Map<String, Object> result = new HashMap<>();
                    result.put("list", new java.util.ArrayList<>());
                    result.put("count", 0);
                    return success(result);
                }
            }
            
            if (conferenceName != null && !conferenceName.isEmpty()) {
                Map<String, String> meetingQuery = new HashMap<>();
                meetingQuery.put("conference_name", conferenceName);
                Map<String, String> meetingConfig = new HashMap<>();
                Query meetingResult = meetingInformationService.select(meetingQuery, meetingConfig);
                List<?> meetingList = meetingResult != null ? meetingResult.getResultList() : null;
                if (meetingList != null && meetingList.size() > 0) {
                    // 如果已经有 meeting_information_id，需要检查是否匹配
                    String existingMeetingId = query.get("meeting_information_id");
                    if (existingMeetingId != null) {
                        // 检查会议ID是否在查询结果中
                        boolean found = false;
                        for (Object meetingObj : meetingList) {
                            if (meetingObj instanceof com.project.demo.entity.MeetingInformation) {
                                Integer meetingId = ((com.project.demo.entity.MeetingInformation) meetingObj).getMeeting_information_id();
                                if (meetingId != null && meetingId.toString().equals(existingMeetingId)) {
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (!found) {
                            // 如果已有 meeting_information_id 但不匹配，返回空列表
                            Map<String, Object> result = new HashMap<>();
                            result.put("list", new java.util.ArrayList<>());
                            result.put("count", 0);
                            return success(result);
                        }
                    } else {
                        // 如果查询结果有多条，可以取第一条或使用 IN 查询
                        // 为了简化，这里取第一条
                        Object meetingObj = meetingList.get(0);
                        if (meetingObj instanceof com.project.demo.entity.MeetingInformation) {
                            Integer meetingId = ((com.project.demo.entity.MeetingInformation) meetingObj).getMeeting_information_id();
                            if (meetingId != null) {
                                query.put("meeting_information_id", meetingId.toString());
                            }
                        }
                    }
                } else {
                    // 如果没有找到匹配的会议，返回空列表
                    Map<String, Object> result = new HashMap<>();
                    result.put("list", new java.util.ArrayList<>());
                    result.put("count", 0);
                    return success(result);
                }
            }
            
            // 处理 user_name 查询：从参会人表中查询
            String userName = query.remove("user_name");
            if (userName != null && !userName.isEmpty()) {
                // 先查询参会人表，获取匹配的 user_participation_id 列表
                Map<String, String> attendeeQuery = new HashMap<>();
                attendeeQuery.put("name", userName);
                Map<String, String> attendeeConfig = new HashMap<>();
                Query attendeeResult = attendeeService.select(attendeeQuery, attendeeConfig);
                List<?> attendeeList = attendeeResult != null ? attendeeResult.getResultList() : null;
                if (attendeeList != null && attendeeList.size() > 0) {
                    java.util.Set<Integer> participationIds = new java.util.HashSet<>();
                    for (Object attendeeObj : attendeeList) {
                        if (attendeeObj instanceof com.project.demo.entity.UserParticipationAttendee) {
                            Integer upId = ((com.project.demo.entity.UserParticipationAttendee) attendeeObj).getUser_participation_id();
                            if (upId != null) {
                                participationIds.add(upId);
                            }
                        } else if (attendeeObj instanceof Map) {
                            @SuppressWarnings("unchecked")
                            Map<String, Object> attendeeMap = (Map<String, Object>) attendeeObj;
                            Object upIdObj = attendeeMap.get("user_participation_id");
                            if (upIdObj != null) {
                                try {
                                    participationIds.add(Integer.parseInt(upIdObj.toString()));
                                } catch (NumberFormatException e) {
                                    log.warn("无法解析 user_participation_id: {}", upIdObj);
                                }
                            }
                        }
                    }
                    if (!participationIds.isEmpty()) {
                        // 构建 SQL WHERE 条件：user_participation_id IN (...)
                        StringBuilder sqlWhere = new StringBuilder("user_participation_id IN (");
                        boolean first = true;
                        for (Integer id : participationIds) {
                            if (!first) {
                                sqlWhere.append(",");
                            }
                            sqlWhere.append(id);
                            first = false;
                        }
                        sqlWhere.append(")");
                        query.put("sqlwhere", sqlWhere.toString());
                    } else {
                        // 如果没有找到匹配的参会人，返回空列表
                        Map<String, Object> result = new HashMap<>();
                        result.put("list", new java.util.ArrayList<>());
                        result.put("count", 0);
                        return success(result);
                    }
                } else {
                    // 如果没有找到匹配的参会人，返回空列表
                    Map<String, Object> result = new HashMap<>();
                    result.put("list", new java.util.ArrayList<>());
                    result.put("count", 0);
                    return success(result);
                }
            }
            
            // 使用标准查询（因为JOIN查询比较复杂，暂时先查询user_participation，然后单独查询会议信息）
            Query resultQuery = service.select(query, config);
            List resultList = resultQuery != null ? resultQuery.getResultList() : null;
            
            // 处理结果，转换为Map格式并JOIN会议信息
            List<Map<String, Object>> list = new java.util.ArrayList<>();
            if (resultList != null) {
                for (Object rowObj : resultList) {
                    Map<String, Object> rowMap = new HashMap<>();
                    
                    if (rowObj instanceof UserParticipation) {
                        UserParticipation up = (UserParticipation) rowObj;
                        rowMap.put("user_participation_id", up.getUser_participation_id());
                        rowMap.put("meeting_information_id", up.getMeeting_information_id());
                        rowMap.put("participants", up.getParticipants());
                        rowMap.put("registration_type", up.getRegistration_type());
                        rowMap.put("accommodation_or_not", up.getAccommodation_or_not());
                        rowMap.put("amount_of_participation", up.getAmount_of_participation());
                        rowMap.put("order_notes", up.getOrder_notes());
                        rowMap.put("examine_state", up.getExamine_state());
                        rowMap.put("pay_state", up.getPay_state());
                        rowMap.put("pay_type", up.getPay_type());
                        rowMap.put("create_time", up.getCreate_time());
                        rowMap.put("update_time", up.getUpdate_time());
                        
                        // JOIN会议信息
                        enrichWithMeetingInfoMap(rowMap);
                        
                        // 加载参会人信息
                        Integer upId = up.getUser_participation_id();
                        if (upId != null) {
                            Map<String, String> attendeeQuery = new HashMap<>();
                            attendeeQuery.put("user_participation_id", upId.toString());
                            Map<String, String> attendeeConfig = new HashMap<>();
                            Query attendeeQueryResult = attendeeService.select(attendeeQuery, attendeeConfig);
                            List attendeeList = attendeeQueryResult != null ? attendeeQueryResult.getResultList() : null;
                            if (attendeeList != null) {
                                rowMap.put("attendees", attendeeList);
                                
                                // 为了兼容前端，也设置 user_name（取第一个参会人姓名）
                                if (attendeeList.size() > 0) {
                                    Object firstAttendee = attendeeList.get(0);
                                    if (firstAttendee instanceof com.project.demo.entity.UserParticipationAttendee) {
                                        com.project.demo.entity.UserParticipationAttendee attendee = (com.project.demo.entity.UserParticipationAttendee) firstAttendee;
                                        rowMap.put("user_name", attendee.getName());
                                    } else if (firstAttendee instanceof Map) {
                                        @SuppressWarnings("unchecked")
                                        Map<String, Object> attendeeMap = (Map<String, Object>) firstAttendee;
                                        rowMap.put("user_name", attendeeMap.get("name"));
                                    }
                                }
                                
                                // 为了兼容前端，设置 accommodation_or_not（如果有任何参会人需要住宿）
                                boolean hasAccommodation = false;
                                for (Object attendeeObj : attendeeList) {
                                    if (attendeeObj instanceof com.project.demo.entity.UserParticipationAttendee) {
                                        com.project.demo.entity.UserParticipationAttendee attendee = (com.project.demo.entity.UserParticipationAttendee) attendeeObj;
                                        if (attendee.getAccommodation() != null && attendee.getAccommodation() == 1) {
                                            hasAccommodation = true;
                                            break;
                                        }
                                    } else if (attendeeObj instanceof Map) {
                                        @SuppressWarnings("unchecked")
                                        Map<String, Object> attendeeMap = (Map<String, Object>) attendeeObj;
                                        Object acc = attendeeMap.get("accommodation");
                                        if (acc != null && (acc.equals(1) || acc.equals("1") || acc.equals(true))) {
                                            hasAccommodation = true;
                                            break;
                                        }
                                    }
                                }
                                rowMap.put("accommodation_or_not", hasAccommodation ? "是" : "否");
                            }
                        }
                        
                        list.add(rowMap);
                    } else if (rowObj instanceof Map) {
                        @SuppressWarnings("unchecked")
                        Map<String, Object> upMap = (Map<String, Object>) rowObj;
                        rowMap.putAll(upMap);
                        enrichWithMeetingInfoMap(rowMap);
                        
                        // 加载参会人信息
                        Object upIdObj = upMap.get("user_participation_id");
                        Integer upId = null;
                        if (upIdObj != null) {
                            upId = Integer.parseInt(upIdObj.toString());
                        }
                        if (upId != null) {
                            Map<String, String> attendeeQuery = new HashMap<>();
                            attendeeQuery.put("user_participation_id", upId.toString());
                            Map<String, String> attendeeConfig = new HashMap<>();
                            Query attendeeQueryResult = attendeeService.select(attendeeQuery, attendeeConfig);
                            List attendeeList = attendeeQueryResult != null ? attendeeQueryResult.getResultList() : null;
                            if (attendeeList != null) {
                                rowMap.put("attendees", attendeeList);
                                
                                // 为了兼容前端，也设置 user_name（取第一个参会人姓名）
                                if (attendeeList.size() > 0) {
                                    Object firstAttendee = attendeeList.get(0);
                                    if (firstAttendee instanceof com.project.demo.entity.UserParticipationAttendee) {
                                        com.project.demo.entity.UserParticipationAttendee attendee = (com.project.demo.entity.UserParticipationAttendee) firstAttendee;
                                        rowMap.put("user_name", attendee.getName());
                                    } else if (firstAttendee instanceof Map) {
                                        @SuppressWarnings("unchecked")
                                        Map<String, Object> attendeeMap = (Map<String, Object>) firstAttendee;
                                        rowMap.put("user_name", attendeeMap.get("name"));
                                    }
                                }
                                
                                // 为了兼容前端，设置 accommodation_or_not（如果有任何参会人需要住宿）
                                boolean hasAccommodation = false;
                                for (Object attendeeObj : attendeeList) {
                                    if (attendeeObj instanceof com.project.demo.entity.UserParticipationAttendee) {
                                        com.project.demo.entity.UserParticipationAttendee attendee = (com.project.demo.entity.UserParticipationAttendee) attendeeObj;
                                        if (attendee.getAccommodation() != null && attendee.getAccommodation() == 1) {
                                            hasAccommodation = true;
                                            break;
                                        }
                                    } else if (attendeeObj instanceof Map) {
                                        @SuppressWarnings("unchecked")
                                        Map<String, Object> attendeeMap = (Map<String, Object>) attendeeObj;
                                        Object acc = attendeeMap.get("accommodation");
                                        if (acc != null && (acc.equals(1) || acc.equals("1") || acc.equals(true))) {
                                            hasAccommodation = true;
                                            break;
                                        }
                                    }
                                }
                                rowMap.put("accommodation_or_not", hasAccommodation ? "是" : "否");
                            }
                        }
                        
                        list.add(rowMap);
                    }
                }
            }
            
            // 获取总数
            Query countQuery = service.count(query, config);
            Object countObj = countQuery.getSingleResult();
            long total = 0;
            if (countObj instanceof Number) {
                total = ((Number) countObj).longValue();
            }
            
            Map<String, Object> result = new HashMap<>();
            result.put("list", list);
            result.put("count", total);
            
            return success(result);
            
        } catch (Exception e) {
            log.error("获取列表失败", e);
            return error(500, "获取列表失败: " + e.getMessage());
        }
    }

    /**
     * 兼容接口：get（等同于get_obj）
     * 用于兼容前端可能的错误调用
     */
    @RequestMapping("/get")
    public Map<String, Object> get(HttpServletRequest request) {
        return obj(request);
    }

    /**
     * 获取支付二维码
     * @param request HTTP请求
     * @return 二维码URL或Base64图片
     */
    @RequestMapping("/get_payment_qrcode")
    public Map<String, Object> getPaymentQrcode(HttpServletRequest request) {
        try {
            Map<String, String> query = service.readQuery(request);
            
            // 获取参数（兼容多种可能的参数名）
            String userParticipationId = query.get("user_participation_id");
            if (userParticipationId == null) {
                userParticipationId = query.get("user_pan_id"); // 兼容可能的错误参数名
            }
            if (userParticipationId == null) {
                userParticipationId = request.getParameter("user_participation_id");
            }
            
            String payType = query.get("pay_type"); // 'wechat' 或 'alipay'
            if (payType == null) {
                payType = request.getParameter("pay_type");
            }
            
            String orderNumber = query.get("order_number");
            if (orderNumber == null) {
                orderNumber = request.getParameter("order_number");
            }
            
            String amount = query.get("amount");
            if (amount == null) {
                amount = request.getParameter("amount");
            }
            
            log.info("支付二维码请求参数 - user_participation_id: {}, pay_type: {}, order_number: {}, amount: {}", 
                userParticipationId, payType, orderNumber, amount);
            
            if (userParticipationId == null || payType == null) {
                log.error("缺少必要参数 - user_participation_id: {}, pay_type: {}", userParticipationId, payType);
                return error(400, "缺少必要参数：user_participation_id 和 pay_type 不能为空");
            }
            
            // 确保订单号不为空
            if (orderNumber == null || orderNumber.isEmpty()) {
                orderNumber = "ORDER_" + userParticipationId + "_" + System.currentTimeMillis();
            }
            
            Map<String, Object> paymentResult;
            
            // 根据支付类型调用相应的支付服务
            if ("wechat".equals(payType)) {
                // 微信支付：金额需要转换为分
                String amountInFen = amount != null ? String.valueOf((int)(Double.parseDouble(amount) * 100)) : "0";
                paymentResult = paymentService.generateWechatQRCode(
                    orderNumber, 
                    amountInFen, 
                    "会议报名费用"
                );
            } else if ("alipay".equals(payType)) {
                // 支付宝支付：金额单位为元
                String amountInYuan = amount != null ? amount : "0.00";
                paymentResult = paymentService.generateAlipayQRCode(
                    orderNumber, 
                    amountInYuan, 
                    "会议报名费用"
                );
            } else {
                return error(400, "不支持的支付类型：" + payType);
            }
            
            // 检查支付服务返回结果
            if (paymentResult.get("success") != null && !Boolean.parseBoolean(paymentResult.get("success").toString())) {
                log.error("支付二维码生成失败：{}", paymentResult.get("message"));
                return error(500, paymentResult.get("message").toString());
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("qrcode_url", paymentResult.get("qrcode_url"));
            result.put("qrcode_content", paymentResult.get("qrcode_content"));
            result.put("order_number", orderNumber);
            result.put("amount", amount);
            result.put("pay_type", payType);
            result.put("mock", paymentResult.get("mock")); // 标识是否为模拟数据
            
            return success(result);
        } catch (Exception e) {
            log.error("获取支付二维码失败", e);
            return error(500, "获取支付二维码失败: " + e.getMessage());
        }
    }

    /**
     * 获取支付宝网页支付链接
     * @param request HTTP请求
     * @return 支付链接
     */
    @RequestMapping("/get_alipay_page_pay")
    public Map<String, Object> getAlipayPagePay(HttpServletRequest request) {
        try {
            Map<String, String> query = service.readQuery(request);
            String userParticipationId = query.get("user_participation_id");
            if (userParticipationId == null) {
                userParticipationId = request.getParameter("user_participation_id");
            }
            
            String orderNumber = query.get("order_number");
            if (orderNumber == null) {
                orderNumber = request.getParameter("order_number");
            }
            
            String amount = query.get("amount");
            if (amount == null) {
                amount = request.getParameter("amount");
            }
            
            String returnUrl = query.get("return_url");
            if (returnUrl == null) {
                returnUrl = request.getParameter("return_url");
            }
            
            log.info("支付宝网页支付请求 - user_participation_id: {}, order_number: {}, amount: {}, return_url: {}", 
                userParticipationId, orderNumber, amount, returnUrl);
            
            if (userParticipationId == null || orderNumber == null || amount == null) {
                return error(400, "缺少必要参数：user_participation_id、order_number 和 amount 不能为空");
            }
            
            // 构建返回URL（支付成功后的跳转地址）
            if (returnUrl == null || returnUrl.isEmpty()) {
                // 默认使用后端回调地址
                String defaultReturnUrl = "http://localhost:5000/api/payment/alipay/return";
                returnUrl = defaultReturnUrl;
                log.warn("未提供return_url，使用默认后端回调地址: {}", defaultReturnUrl);
            } else {
                log.info("使用前端提供的return_url: {}", returnUrl);
            }
            
            // 验证return_url格式
            if (!returnUrl.startsWith("http://") && !returnUrl.startsWith("https://")) {
                log.error("return_url格式错误，必须是完整的HTTP/HTTPS URL: {}", returnUrl);
                return error(400, "return_url格式错误，必须是完整的HTTP/HTTPS URL");
            }
            
            // 调用支付服务生成网页支付链接
            Map<String, Object> paymentResult = paymentService.generateAlipayPagePay(
                orderNumber,
                amount,
                "会议报名费用",
                returnUrl
            );
            
            // 检查支付服务返回结果
            if (paymentResult.get("success") != null && !Boolean.parseBoolean(paymentResult.get("success").toString())) {
                log.error("支付宝网页支付链接生成失败：{}", paymentResult.get("message"));
                return error(500, paymentResult.get("message").toString());
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("pay_url", paymentResult.get("pay_url"));
            result.put("order_number", paymentResult.get("order_number"));
            result.put("sandbox_warning", paymentResult.get("sandbox_warning"));
            
            return success(result);
        } catch (Exception e) {
            log.error("获取支付宝网页支付链接失败", e);
            return error(500, "获取支付链接失败: " + e.getMessage());
        }
    }

    /**
     * 获取统计数据
     * @return 统计数据
     */
    @RequestMapping("/statistics")
    public Map<String, Object> statistics(HttpServletRequest request) {
        try {
            Map<String, Object> result = new HashMap<>();
            
            // 获取总报名人数（统计所有记录，不应用查询条件）
            Map<String, String> emptyQuery = new HashMap<>();
            Map<String, String> emptyConfig = new HashMap<>();
            Query totalQuery = service.count(emptyQuery, emptyConfig);
            Object totalCountObj = totalQuery != null ? totalQuery.getSingleResult() : null;
            Long totalCount = null;
            if (totalCountObj != null) {
                if (totalCountObj instanceof Long) {
                    totalCount = (Long) totalCountObj;
                } else if (totalCountObj instanceof Number) {
                    totalCount = ((Number) totalCountObj).longValue();
                } else {
                    try {
                        totalCount = Long.parseLong(totalCountObj.toString());
                    } catch (NumberFormatException e) {
                        log.warn("总人数格式转换失败: {}", totalCountObj);
                    }
                }
            }
            log.info("总报名人数查询结果: {}", totalCount);
            
            // 获取已支付人数（检查多种可能的支付状态值）
            Map<String, String> paidQuery = new HashMap<>();
            paidQuery.put("pay_state", "已支付");
            Query paidCountQuery = service.count(paidQuery, emptyConfig);
            Object paidCountObj = paidCountQuery != null ? paidCountQuery.getSingleResult() : null;
            Long paidCount = null;
            if (paidCountObj != null) {
                if (paidCountObj instanceof Long) {
                    paidCount = (Long) paidCountObj;
                } else if (paidCountObj instanceof Number) {
                    paidCount = ((Number) paidCountObj).longValue();
                } else {
                    try {
                        paidCount = Long.parseLong(paidCountObj.toString());
                    } catch (NumberFormatException e) {
                        log.warn("已支付人数格式转换失败: {}", paidCountObj);
                    }
                }
            }
            log.info("已支付人数查询结果（pay_state='已支付'）: {}", paidCount);
            
            // 获取待支付人数（数据库可能使用"未支付"而不是"待支付"）
            // 先查询"待支付"
            Map<String, String> unpaidQuery1 = new HashMap<>();
            unpaidQuery1.put("pay_state", "待支付");
            Query unpaidCountQuery1 = service.count(unpaidQuery1, emptyConfig);
            Object unpaidCountObj1 = unpaidCountQuery1 != null ? unpaidCountQuery1.getSingleResult() : null;
            Long unpaidCount1 = 0L;
            if (unpaidCountObj1 != null) {
                if (unpaidCountObj1 instanceof Number) {
                    unpaidCount1 = ((Number) unpaidCountObj1).longValue();
                }
            }
            
            // 再查询"未支付"
            Map<String, String> unpaidQuery2 = new HashMap<>();
            unpaidQuery2.put("pay_state", "未支付");
            Query unpaidCountQuery2 = service.count(unpaidQuery2, emptyConfig);
            Object unpaidCountObj2 = unpaidCountQuery2 != null ? unpaidCountQuery2.getSingleResult() : null;
            Long unpaidCount2 = 0L;
            if (unpaidCountObj2 != null) {
                if (unpaidCountObj2 instanceof Number) {
                    unpaidCount2 = ((Number) unpaidCountObj2).longValue();
                }
            }
            
            // 合计：待支付 + 未支付
            Long unpaidCount = unpaidCount1 + unpaidCount2;
            log.info("待支付人数查询结果 - '待支付': {}, '未支付': {}, 合计: {}", unpaidCount1, unpaidCount2, unpaidCount);
            
            // 如果还是0，查询所有非"已支付"的记录（包括null、空字符串等）
            if (unpaidCount == null || unpaidCount == 0) {
                try {
                    String allUnpaidSql = "SELECT COUNT(*) FROM `user_participation` WHERE (`pay_state` IS NULL OR `pay_state` = '' OR (`pay_state` != '已支付' AND `pay_state` IS NOT NULL))";
                    Query allUnpaidQuery = service.runCountSql(allUnpaidSql);
                    Object allUnpaidObj = allUnpaidQuery.getSingleResult();
                    if (allUnpaidObj != null && allUnpaidObj instanceof Number) {
                        unpaidCount = ((Number) allUnpaidObj).longValue();
                        log.info("所有非已支付记录数: {}", unpaidCount);
                    }
                } catch (Exception e) {
                    log.warn("查询所有非已支付记录失败: {}", e.getMessage());
                }
            }
            
            // 获取总金额（实际计算所有记录的 amount_of_participation 之和）
            Map<String, String> totalAmountConfig = new HashMap<>();
            totalAmountConfig.put(FindConfig.FIELD, "amount_of_participation");
            Map<String, String> emptyQueryForSum = new HashMap<>();
            Query totalAmountQuery = service.sum(emptyQueryForSum, totalAmountConfig);
            Object totalAmountObj = totalAmountQuery != null ? totalAmountQuery.getSingleResult() : null;
            double totalAmount = 0.0;
            log.info("总金额查询结果: {}, 类型: {}", totalAmountObj, totalAmountObj != null ? totalAmountObj.getClass().getName() : "null");
            if (totalAmountObj != null) {
                if (totalAmountObj instanceof Number) {
                    totalAmount = ((Number) totalAmountObj).doubleValue();
                    log.info("总金额（Number）: {}", totalAmount);
                } else {
                    try {
                        totalAmount = Double.parseDouble(totalAmountObj.toString());
                        log.info("总金额（String转）: {}", totalAmount);
                    } catch (NumberFormatException e) {
                        log.warn("总金额格式转换失败: {}, 错误: {}", totalAmountObj, e.getMessage());
                    }
                }
            } else {
                log.warn("总金额查询结果为null");
            }
            
            // 获取已支付金额（实际计算已支付记录的 amount_of_participation 之和）
            // 注意：amount_of_participation 在数据库中可能是整数（以分为单位或直接以元为单位）
            // 需要根据实际存储格式处理
            Map<String, String> paidAmountConfig = new HashMap<>();
            paidAmountConfig.put(FindConfig.FIELD, "amount_of_participation");
            Query paidAmountQuery = service.sum(paidQuery, paidAmountConfig);
            Object paidAmountObj = paidAmountQuery != null ? paidAmountQuery.getSingleResult() : null;
            double paidAmount = 0.0;
            log.info("已支付金额查询结果: {}, 类型: {}", paidAmountObj, paidAmountObj != null ? paidAmountObj.getClass().getName() : "null");
            if (paidAmountObj != null) {
                if (paidAmountObj instanceof Number) {
                    paidAmount = ((Number) paidAmountObj).doubleValue();
                    log.info("已支付金额（Number）: {}", paidAmount);
                } else {
                    try {
                        paidAmount = Double.parseDouble(paidAmountObj.toString());
                        log.info("已支付金额（String转）: {}", paidAmount);
                    } catch (NumberFormatException e) {
                        log.warn("已支付金额格式转换失败: {}, 错误: {}", paidAmountObj, e.getMessage());
                    }
                }
            } else {
                log.warn("已支付金额查询结果为null");
            }
            
            // 获取今日新增（实际查询今天创建的记录数）
            long todayIncrease = 0;
            try {
                // 获取今天的日期字符串（格式：YYYY-MM-DD）
                java.text.SimpleDateFormat dateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd");
                String todayStr = dateFormat.format(new java.util.Date());
                
                // 使用原生SQL查询今日新增
                String todayCountSql = "SELECT COUNT(*) FROM `user_participation` WHERE DATE(`create_time`) = '" + todayStr + "'";
                Query todayCountQuery = service.runCountSql(todayCountSql);
                Object todayCountObj = todayCountQuery.getSingleResult();
                if (todayCountObj != null) {
                    if (todayCountObj instanceof Number) {
                        todayIncrease = ((Number) todayCountObj).longValue();
                    } else {
                        try {
                            todayIncrease = Long.parseLong(todayCountObj.toString());
                        } catch (NumberFormatException e) {
                            log.warn("今日新增数量格式转换失败: {}", todayCountObj);
                        }
                    }
                }
                log.info("今日新增记录数: {}", todayIncrease);
            } catch (Exception e) {
                log.warn("计算今日新增失败: {}", e.getMessage());
                todayIncrease = 0; // 如果计算失败，暂时设为0
            }
            
            // 确保所有返回值都是数字类型，不能为null
            int totalParticipantsValue = totalCount != null ? totalCount.intValue() : 0;
            int paidCountValue = paidCount != null ? paidCount.intValue() : 0;
            int unpaidCountValue = unpaidCount != null ? unpaidCount.intValue() : 0;
            
            result.put("totalParticipants", totalParticipantsValue);
            result.put("paidCount", paidCountValue);
            result.put("unpaidCount", unpaidCountValue);
            result.put("totalAmount", totalAmount);
            result.put("paidAmount", paidAmount);
            result.put("todayIncrease", (int)todayIncrease);
            
            log.info("=== 统计数据汇总 ===");
            log.info("总人数: {} (原始值: {})", totalParticipantsValue, totalCount);
            log.info("已支付: {} (原始值: {})", paidCountValue, paidCount);
            log.info("待支付: {} (原始值: {})", unpaidCountValue, unpaidCount);
            log.info("总金额: {}", totalAmount);
            log.info("已支付金额: {}", paidAmount);
            log.info("今日新增: {}", todayIncrease);
            log.info("返回的完整result Map: {}", result);
            
            // 直接返回原始 Map，不经过 covertObject 转换（避免字段名被转换为下划线）
            Map<String, Object> response = new HashMap<>();
            response.put("result", result);
            return response;
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            return error(500, "获取统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取报名趋势数据（按日期统计所有历史数据）
     * @return 按日期统计的报名数量
     */
    @RequestMapping("/trend_statistics")
    public Map<String, Object> trendStatistics() {
        try {
            log.info("获取报名趋势统计数据（所有历史数据）");
            
            // 使用SQL查询按日期统计报名数量
            // 使用 DATE(create_time) 按日期分组，获取所有历史数据
            // 注意：如果create_time是TIMESTAMP类型，MySQL的DATE()函数可以正确处理
            String trendSql = "SELECT DATE(create_time) as date, COUNT(*) as count " +
                             "FROM user_participation " +
                             "WHERE create_time IS NOT NULL " +
                             "GROUP BY DATE(create_time) " +
                             "ORDER BY DATE(create_time) ASC";
            
            log.info("执行趋势统计SQL: {}", trendSql);
            
            // 先检查是否有数据
            String checkSql = "SELECT COUNT(*) FROM user_participation WHERE create_time IS NOT NULL";
            javax.persistence.Query checkQuery = service.runCountSql(checkSql);
            Object totalCount = checkQuery.getSingleResult();
            log.info("数据库中总记录数（create_time不为空）: {}", totalCount);
            
            // 如果总记录数为0，直接返回空结果
            if (totalCount != null && totalCount instanceof Number) {
                long count = ((Number) totalCount).longValue();
                if (count == 0) {
                    log.warn("数据库中没有任何记录（create_time不为空），返回空趋势数据");
                    Map<String, Object> result = new HashMap<>();
                    result.put("trendData", new java.util.ArrayList<>());
                    result.put("totalDays", 0);
                    return success(result);
                }
            }
            
            // 使用 runCountSql 执行原生 SQL 查询（不指定实体类型）
            javax.persistence.Query trendQuery = service.runCountSql(trendSql);
            List<?> results = trendQuery.getResultList();
            
            log.info("SQL查询返回结果数: {}", results != null ? results.size() : 0);
            
            // 详细打印查询结果的前几条，用于调试
            if (results != null && results.size() > 0) {
                log.info("查询结果详情（前3条）:");
                for (int i = 0; i < Math.min(3, results.size()); i++) {
                    Object rowObj = results.get(i);
                    log.info("  结果[{}]: {}", i, rowObj);
                    log.info("  结果[{}]类型: {}", i, rowObj != null ? rowObj.getClass().getName() : "null");
                    if (rowObj instanceof Object[]) {
                        Object[] row = (Object[]) rowObj;
                        log.info("  结果[{}]是数组，长度: {}", i, row.length);
                        for (int j = 0; j < row.length; j++) {
                            log.info("    列[{}]: {} (类型: {})", j, row[j], row[j] != null ? row[j].getClass().getName() : "null");
                        }
                    }
                }
            } else {
                log.warn("⚠️ SQL查询返回空结果！");
                log.warn("可能原因：1) 数据库中没有数据 2) create_time字段全为NULL 3) SQL查询有误");
            }
            
            // 转换为前端需要的格式
            List<Map<String, Object>> trendData = new java.util.ArrayList<>();
            
            if (results != null && !results.isEmpty()) {
                log.info("开始处理 {} 条查询结果", results.size());
                for (int index = 0; index < results.size(); index++) {
                    Object rowObj = results.get(index);
                    try {
                        Object[] row;
                        // 处理不同的返回类型
                        if (rowObj instanceof Object[]) {
                            row = (Object[]) rowObj;
                            log.debug("处理结果[{}]: 数组类型，长度: {}", index, row.length);
                        } else {
                            // 如果不是数组，可能是其他格式
                            log.warn("结果[{}]意外的行数据类型: {}", index, rowObj != null ? rowObj.getClass().getName() : "null");
                            log.warn("结果[{}]内容: {}", index, rowObj);
                            continue;
                        }
                        
                        if (row.length < 2) {
                            log.error("结果[{}]行数据列数不足，期望2列，实际: {}", index, row.length);
                            continue;
                        }
                        
                        log.debug("结果[{}]列0 (日期): {} (类型: {})", index, row[0], row[0] != null ? row[0].getClass().getName() : "null");
                        log.debug("结果[{}]列1 (数量): {} (类型: {})", index, row[1], row[1] != null ? row[1].getClass().getName() : "null");
                        
                        Map<String, Object> item = new HashMap<>();
                        
                        // row[0] 是日期（可能是 java.sql.Date、java.util.Date 或 String）
                        // row[1] 是数量（Long、Integer 或 Number）
                        Object dateObj = row[0];
                        Object countObj = row[1];
                        
                        if (dateObj == null || countObj == null) {
                            log.warn("日期或数量为空，跳过该记录");
                            continue;
                        }
                        
                        // 处理日期
                        java.util.Date date;
                        if (dateObj instanceof java.sql.Date) {
                            date = (java.sql.Date) dateObj;
                        } else if (dateObj instanceof java.util.Date) {
                            date = (java.util.Date) dateObj;
                        } else if (dateObj instanceof String) {
                            // 尝试解析字符串日期
                            java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                            date = sdf.parse((String) dateObj);
                        } else {
                            log.warn("无法处理的日期类型: {}", dateObj.getClass().getName());
                            continue;
                        }
                        
                        // 处理数量
                        Long count;
                        if (countObj instanceof Number) {
                            count = ((Number) countObj).longValue();
                        } else {
                            count = Long.parseLong(countObj.toString());
                        }
                        
                        // 格式化日期为 YYYY-MM-DD
                        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
                        String dateStr = sdf.format(date);
                        
                        // 格式化标签为 MM/DD
                        java.text.SimpleDateFormat labelSdf = new java.text.SimpleDateFormat("MM/dd");
                        String label = labelSdf.format(date);
                        
                        item.put("date", dateStr);
                        item.put("label", label);
                        item.put("count", count.intValue());
                        
                        trendData.add(item);
                        
                        log.info("✅ 成功处理趋势数据[{}] - 日期: {}, 标签: {}, 数量: {}", index, dateStr, label, count);
                    } catch (Exception e) {
                        log.error("❌ 处理趋势数据行[{}]时发生错误", index, e);
                        log.error("错误数据内容: row[0]={}, row[1]={}", rowObj, rowObj instanceof Object[] ? ((Object[])rowObj)[1] : "N/A");
                        continue;
                    }
                }
            } else {
                log.warn("⚠️ results 为空或 null，无法处理趋势数据");
            }
            
            log.info("报名趋势统计数据查询完成，共 {} 条记录", trendData.size());
            
            if (trendData.isEmpty()) {
                log.warn("⚠️ 趋势数据为空，可能数据库中没有数据");
            }
            
            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("trendData", trendData);
            result.put("totalDays", trendData.size());
            
            return success(result);
        } catch (Exception e) {
            log.error("获取报名趋势统计数据失败", e);
            return error(500, "获取报名趋势统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 获取报名时间分布数据（按月份统计）
     * @return 按月份统计的报名数量
     */
    @RequestMapping("/monthly_statistics")
    public Map<String, Object> monthlyStatistics() {
        try {
            log.info("获取报名时间分布统计数据（按月份统计）");
            
            // 使用SQL查询按月份统计报名数量
            String monthlySql = "SELECT DATE_FORMAT(create_time, '%Y-%m') as month, COUNT(*) as count " +
                               "FROM user_participation " +
                               "WHERE create_time IS NOT NULL " +
                               "GROUP BY DATE_FORMAT(create_time, '%Y-%m') " +
                               "ORDER BY DATE_FORMAT(create_time, '%Y-%m') ASC";
            
            log.info("执行月份统计SQL: {}", monthlySql);
            
            Query monthlyQuery = service.runCountSql(monthlySql);
            @SuppressWarnings("unchecked")
            List<Object[]> monthlyResults = monthlyQuery.getResultList();
            
            log.info("数据库中总记录数（create_time不为空）: {}", monthlyResults.size());
            log.info("SQL查询返回结果数: {}", monthlyResults.size());
            
            List<Map<String, Object>> monthlyData = new java.util.ArrayList<>();
            
            if (monthlyResults != null && monthlyResults.size() > 0) {
                log.info("开始处理 {} 条查询结果", monthlyResults.size());
                
                for (int i = 0; i < monthlyResults.size(); i++) {
                    Object[] row = monthlyResults.get(i);
                    if (row == null || row.length < 2) {
                        log.warn("结果[{}]数据不完整，跳过", i);
                        continue;
                    }
                    
                    try {
                        // 提取月份（格式：YYYY-MM）
                        String monthKey = null;
                        if (row[0] != null) {
                            monthKey = row[0].toString();
                        }
                        
                        // 提取数量
                        long count = 0;
                        if (row[1] != null) {
                            if (row[1] instanceof Number) {
                                count = ((Number) row[1]).longValue();
                            } else {
                                try {
                                    count = Long.parseLong(row[1].toString());
                                } catch (NumberFormatException e) {
                                    log.warn("数量格式转换失败: {}", row[1]);
                                }
                            }
                        }
                        
                        if (monthKey != null) {
                            // 格式化为 "YYYY年MM月"
                            String[] parts = monthKey.split("-");
                            String label = parts[0] + "年" + parts[1] + "月";
                            
                            Map<String, Object> monthItem = new HashMap<>();
                            monthItem.put("month", monthKey);
                            monthItem.put("label", label);
                            monthItem.put("count", count);
                            
                            monthlyData.add(monthItem);
                            
                            log.info("✅ 成功处理月份数据[{}] - 月份: {}, 标签: {}, 数量: {}", 
                                    i, monthKey, label, count);
                        }
                    } catch (Exception e) {
                        log.error("处理月份数据[{}]失败: {}", i, e.getMessage(), e);
                    }
                }
            } else {
                log.warn("月份统计数据查询结果为空");
            }
            
            log.info("报名时间分布统计数据查询完成，共 {} 条记录", monthlyData.size());
            
            Map<String, Object> result = new HashMap<>();
            result.put("monthly_data", monthlyData);
            
            return success(result);
        } catch (Exception e) {
            log.error("获取报名时间分布统计数据失败", e);
            return error(500, "获取报名时间分布统计数据失败: " + e.getMessage());
        }
    }

    /**
     * 导出Excel
     * @param request HTTP请求
     * @return 导出文件URL
     */
    @RequestMapping("/export_excel")
    public Map<String, Object> exportExcel(HttpServletRequest request) {
        try {
            Map<String, String> query = service.readQuery(request);
            Map<String, String> config = service.readConfig(request);
            
            // 获取数据列表
            Query select = service.select(query, config);
            @SuppressWarnings("unchecked")
            List<UserParticipation> list = select.getResultList();
            
            log.info("导出Excel请求，记录数: {}", list != null ? list.size() : 0);
            
            // 返回下载URL
            Map<String, Object> result = new HashMap<>();
            result.put("bl", true);
            result.put("url", "/api/user_participation/export_excel_download?timestamp=" + System.currentTimeMillis());
            result.put("tip", "导出成功，共" + (list != null ? list.size() : 0) + "条记录");
            
            return success(result);
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            return error(500, "导出Excel失败: " + e.getMessage());
        }
    }

    /**
     * 下载Excel文件
     * @param request HTTP请求
     * @param response HTTP响应
     */
    @GetMapping("/export_excel_download")
    public void exportExcelDownload(HttpServletRequest request, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            Map<String, String> query = service.readQuery(request);
            Map<String, String> config = service.readConfig(request);
            
            // 使用 BaseService 的 exportDb 方法生成 Excel
            HSSFWorkbook workbook = service.exportDb(query, config);
            
            // 设置响应头
            String fileName = "用户报名数据_" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".xls";
            String encodedFileName = java.net.URLEncoder.encode(fileName, "UTF-8").replace("+", "%20");
            
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");
            
            // 写入响应流
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.flush();
            
            log.info("Excel导出成功，文件名: {}", fileName);
        } catch (Exception e) {
            log.error("下载Excel文件失败", e);
            try {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                response.setContentType("text/plain; charset=UTF-8");
                if (outputStream != null) {
                    outputStream.write(("导出失败: " + e.getMessage()).getBytes("UTF-8"));
                }
            } catch (IOException ioException) {
                log.error("写入错误响应失败", ioException);
            }
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("关闭输出流失败", e);
            }
        }
    }

}
